import os
import subprocess
import re
from docx import Document
from Data import search_file

sysop_flag = False


# 目录编号
def module_level_number_en(flag, is_only_dir):
    global sysop_flag
    # 添加路径处理函数
    # def process_path(path):
    #     return path.replace('&', '^&')
    if is_only_dir is None:
        filepaths = search_file.select_folder()
        return filepaths
    root_path = None
    filepaths = search_file.select_folder()
    # print(filepaths)
    if filepaths == "-1":
        return "-1"
    updated_paths = filepaths
    count = 0
    for path in filepaths:
        if "01-配置指南" in path.split('\\')[-3]:
            if count == 0:
                root_path = path.rsplit("01-配置指南", 1)[0]
            count = count + 1

    if root_path is None:
        print("\033[91m错误：未能找到有效的根目录路径\033[0m")
        print("请检查配置指南与命令参考编号")
        print("程序执行完成!!!")
        return "-1"

    scg_path = f'{root_path}01-配置指南'
    cref_path = f'{root_path}02-命令参考'
    flyleaf_path = f'{root_path}封面和扉页'
    # 检查封面和扉页文件夹是否存在
    flyleaf_path_flag = False
    if os.path.exists(flyleaf_path):
        flyleaf_path_flag = True
    else:
        flag1 = True
        flag2 = True
        scg_flyleaf_path = f'{root_path}\\01-配置指南\\00-封面'
        cref_flyleaf_path = f'{root_path}\\02-命令参考\\00-封面'
        if not os.path.exists(scg_flyleaf_path):
            print(f"\033[91m错误：找不到配置指南封面和扉页文件夹:\033[0m {scg_flyleaf_path}")
            sysop_flag = True
            flag1 = False
        if not os.path.exists(cref_flyleaf_path):
            print(f"\033[91m错误：找不到命令参考封面和扉页文件夹:\033[0m {cref_flyleaf_path}")
            sysop_flag = True
            flag2 = False
        if not flag1 and not flag2:
            print("不存在00-封面文件夹")
            return "-1"

        # else:
        #     flyleaf_path_flag = True
    # 遍历封面和扉页文件夹
    try:
        content = []  # 将content初始化移到这里
        if flyleaf_path_flag:
            # 递归遍历主封面目录及其子目录
            for root, dirs, files in os.walk(flyleaf_path):
                for file in files:
                    if file.endswith('.docx'):
                        if "配置" in root.rsplit('\\', 1)[1]:
                            scg_flyleaf_path = f'{root}\\Title page.docx'
                            # print(root_path)
                            # 读取配置指南扉页内容
                            doc = Document(scg_flyleaf_path)
                            manual_found = False

                            # 遍历段落查找"手册"之后的内容
                            for para in doc.paragraphs:
                                if "Configuration Guide" in para.text:
                                    manual_found = True
                                    continue
                                if manual_found and para.text.strip():
                                    # 添加序号，从01开始
                                    index = len(content) + 1
                                    formatted_text = f"{index:02d}-{para.text.strip()}"
                                    content.append(formatted_text)
                            break
        else:
            # 使用配置指南的扉页
            scg_flyleaf_path = f'{root_path}\\01-配置指南\\00-封面\\Title page.docx'
            # 读取配置指南扉页内容
            doc = Document(scg_flyleaf_path)
            manual_found = False

            # 遍历段落查找"手册"之后的内容
            for para in doc.paragraphs:
                if "Configuration Guide" in para.text:
                    manual_found = True
                    continue
                if manual_found and para.text.strip():
                    # 添加序号，从01开始
                    index = len(content) + 1
                    formatted_text = f"{index:02d}-{para.text.strip()}"
                    content.append(formatted_text)

        # 打印扉页内容进行调试
        # print("扉页中的分册列表：")
        # for item in content:
        #     print(item)
        # print("------------------------")

        # 定义映射表
        name_mapping = {
            'Basic Configuration': '基础配置',
            'Alarm Management': '设备管理',
            'Interface': '接口',
            'Virtualization': '虚拟化',
            'Ethernet Switching': '以太网交换',
            'IP Service': 'IP业务',
            'IP Routing': 'IP路由',
            'Multicast': '组播',
            'MPLS': 'MPLS',
            'ACL and QoS': 'ACL和QoS',
            'Security': '安全',
            'Reliability': '可靠性',
            'Network Control and Monitoring': '网管与监控',
            'Lossless Network': '无损网络',
            'VPN': 'VPN',
            'Data Center': '数据中心'
        }

        # 遍历配置指南目录
        scg_folders = []
        if os.path.exists(scg_path):
            for folder in os.listdir(scg_path):
                folder_path = os.path.join(scg_path, folder)
                if os.path.isdir(folder_path) and folder != "00-pdf" and folder != "00-封面":
                    scg_folders.append(folder)

            # print("实际目录中的分册：")
            # for folder in scg_folders:
            #     print(folder)
            # print("------------------------")

            # 创建扉页分册名称集合（只包含英文名称）
            flyleaf_names = set()
            for name in content:
                _, en_name = name.split('-', 1)
                flyleaf_names.add(en_name.strip())

            # 检查目录中存在但扉页中不存在的分册（命令参考部分）
            name_mapping_reverse = {v: k for k, v in name_mapping.items()}
            for folder in scg_folders:
                # 处理目录未编号
                if "-" in folder:
                    _, folder_name = folder.split('-', 1)
                else:
                    folder_name = folder
                # 检查目录名是否为英文
                if folder_name in name_mapping_reverse:
                    # 中文目录通过映射表转换
                    en_name = name_mapping_reverse[folder_name]
                    if en_name not in flyleaf_names:
                        print(f"\033[93m警告：配置指南分册 '{folder}' 在扉页中未找到对应的英文名称 '{en_name}'\033[0m")
                        sysop_flag = True
                else:
                    # 英文目录处理
                    folder_name_clean = ' '.join(folder_name.split())

                    if folder_name_clean == 'Basic Configuration':
                        folder_name_clean = 'Basic Configuration'
                    else:
                        folder_name_clean = folder_name_clean.replace(' Configuration', '')
                    if not any(en_name.strip() == folder_name_clean for en_name in flyleaf_names):
                        print(f"\033[93m警告：配置指南分册 '{folder}' 在扉页中未找到\033[0m")
                        sysop_flag = True

            # 检查扉页中的分册是否存在于目录中
            for name in content:
                match_found = False
                num, en_name = name.split('-', 1)
                en_name = en_name.strip()

                for folder in scg_folders:
                    if "-" in folder:
                        folder_num, folder_name = folder.split('-', 1)
                    else:
                        folder_name = folder
                        folder_num = None
                    # 检查目录名是否为中文
                    pattern = re.compile(r'[\u4e00-\u9fa5]')
                    if bool(pattern.search(folder_name)):
                        # 中文目录处理
                        if folder_name in name_mapping.values():
                            # 通过反向映射表获取英文名称
                            for en_key, zh_value in name_mapping.items():
                                if zh_value == folder_name and en_key == en_name:
                                    match_found = True
                                    if num != folder_num:
                                        try:
                                            old_path = os.path.join(scg_path, folder)
                                            new_name = f"{num}-{folder_name}"
                                            new_path = os.path.join(scg_path, new_name)
                                            if flag:
                                                subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                            else:
                                                os.rename(old_path, new_path)
                                            print(f"重命名文件夹: {folder} -> {new_name}")
                                            for i, updated_path in enumerate(updated_paths):
                                                if old_path in updated_path:
                                                    updated_paths[i] = updated_path.replace(old_path, new_path)
                                        except Exception as e:
                                            print(f"\033[91m重命名文件夹失败:\033[0m {str(e)}")
                                            sysop_flag = True
                                    break
                    else:
                        # 英文目录处理
                        folder_name_clean = ' '.join(folder_name.split())

                        if folder_name_clean == 'Basic Configuration':
                            folder_name_clean = 'Basic Configuration'
                        else:
                            folder_name_clean = folder_name_clean.replace(' Configuration', '')

                        # 直接比对清理后的名称
                        if folder_name_clean == en_name:
                            match_found = True
                            if num != folder_num:
                                try:
                                    old_path = os.path.join(scg_path, folder)
                                    new_name = f"{num}-{folder_name}"
                                    new_path = os.path.join(scg_path, new_name)
                                    if flag:
                                        subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                    else:
                                        os.rename(old_path, new_path)
                                    print(f"重命名文件夹: {folder} -> {new_name}")
                                    for i, updated_path in enumerate(updated_paths):
                                        if old_path in updated_path:
                                            updated_paths[i] = updated_path.replace(old_path, new_path)
                                except Exception as e:
                                    print(f"\033[91m重命名文件夹失败:\033[0m {str(e)}")
                                    sysop_flag = True
                            break

                if not match_found:
                    print(f"\033[93m警告：扉页中的 '{name}' 在配置指南中未找到对应的分册\033[0m")
                    sysop_flag = True
        else:
            print(f"\033[91m错误：找不到配置指南目录:\033[0m {scg_path}")
            sysop_flag = True

    except Exception as e:
        print(f"\033[91m处理文件出错:\033[0m {str(e)}")
        print(f"\033[91m遍历文件夹出错:\033[0m {str(e)}")
        sysop_flag = True
    print("配置指南处理完成！！！")

    # 遍历封面和扉页文件夹
    try:
        content = []  # 将content初始化移到这里
        if flyleaf_path_flag:
            # 递归遍历主封面目录及其子目录
            for root, dirs, files in os.walk(flyleaf_path):
                for file in files:
                    if file.endswith('.docx'):
                        if "命令" in root.rsplit('\\', 1)[1]:
                            cref_flyleaf_path = f'{root}\\Title page.docx'
                            # 读取配置指南扉页内容
                            doc = Document(cref_flyleaf_path)
                            manual_found = False

                            # 遍历段落查找"手册"之后的内容
                            for para in doc.paragraphs:
                                if "Command Reference" in para.text:
                                    manual_found = True
                                    continue
                                if manual_found and para.text.strip():
                                    # 添加序号，从01开始
                                    index = len(content) + 1
                                    formatted_text = f"{index:02d}-{para.text.strip()}"
                                    content.append(formatted_text)
                            break
        else:
            # 使用命令参考的扉页
            cref_flyleaf_path = f'{root_path}\\02-命令参考\\00-封面\\Title page.docx'
            # 读取命令参考扉页内容
            doc = Document(cref_flyleaf_path)
            manual_found = False

            # 遍历段落查找"手册"之后的内容
            for para in doc.paragraphs:
                if "Command Reference" in para.text:
                    manual_found = True
                    continue
                if manual_found and para.text.strip():
                    # 添加序号，从01开始
                    index = len(content) + 1
                    formatted_text = f"{index:02d}-{para.text.strip()}"
                    content.append(formatted_text)

        # 打印扉页内容进行调试
        # print("扉页中的分册列表：")
        # for item in content:
        #     print(item)
        # print("------------------------")

        # 定义映射表
        name_mapping = {
            'Basic Configuration': '基础配置',
            'Alarm Management': '设备管理',
            'Interface': '接口',
            'Virtualization': '虚拟化',
            'Ethernet Switching': '以太网交换',
            'IP Service': 'IP业务',
            'IP Routing': 'IP路由',
            'Multicast': '组播',
            'MPLS': 'MPLS',
            'ACL and QoS': 'ACL和QoS',
            'Security': '安全',
            'Reliability': '可靠性',
            'Network Control and Monitoring': '网管与监控',
            'Lossless Network': '无损网络',
            'VPN': 'VPN',
            'Data Center': '数据中心'
        }

        # 遍历命令参考目录
        cref_folders = []
        if os.path.exists(cref_path):
            for folder in os.listdir(cref_path):
                folder_path = os.path.join(cref_path, folder)
                if os.path.isdir(folder_path) and folder != "00-pdf" and folder != "00-封面":
                    cref_folders.append(folder)

            # print("实际目录中的分册：")
            # for folder in cref_folders:
            #     print(folder)
            # print("------------------------")

            # 创建扉页分册名称集合（只包含英文名称）
            flyleaf_names = set()
            for name in content:
                _, en_name = name.split('-', 1)
                flyleaf_names.add(en_name.strip())

            # 检查目录中存在但扉页中不存在的分册
            # 检查目录中存在但扉页中不存在的分册
            for folder in cref_folders:
                if "-" in folder:
                    folder_num, folder_name = folder.split('-', 1)
                else:
                    folder_num = None
                    folder_name = folder
                # 检查目录名是否为中文
                pattern = re.compile(r'[\u4e00-\u9fa5]')
                if bool(pattern.search(folder_name)):
                    # 中文目录处理
                    if folder_name in name_mapping.values():
                        # 通过反向映射表获取英文名称
                        for en_name, zh_name in name_mapping.items():
                            if zh_name == folder_name:
                                folder_name_clean = en_name
                                break
                        # 检查扉页名称是否包含目录名称
                        if not any(folder_name_clean in en_name.strip() for en_name in flyleaf_names):
                            print(f"\033[93m警告：命令参考分册 '{folder}' 在扉页中未找到对应的英文名称 '{en_name}'\033[0m")
                            sysop_flag = True
                    else:
                        print(f"\033[93m警告：命令参考分册 '{folder}' 在映射表中未找到对应的英文名称\033[0m")
                        sysop_flag = True
                else:
                    # 英文目录处理
                    folder_name_clean = ' '.join(folder_name.split())
                    # 对于非Basic Commands目录，去除Commands
                    if folder_name_clean == 'Basic Commands':
                        folder_name_clean = 'Basic Configuration'
                    else:
                        folder_name_clean = folder_name_clean.replace(' Commands', '')
                    # 修改比对逻辑：检查扉页名称是否包含目录名称
                    if not any(folder_name_clean in en_name.strip() for en_name in flyleaf_names):
                        print(f"\033[93m警告：命令参考分册 '{folder}' 在扉页中未找到\033[0m")
                        sysop_flag = True

            # 检查扉页中的分册是否存在于目录中
            for name in content:
                match_found = False
                num, en_name = name.split('-', 1)
                en_name = en_name.strip()

                for folder in cref_folders:
                    if "-" in folder:
                        folder_num, folder_name = folder.split('-', 1)
                    else:
                        folder_num = None
                        folder_name = folder
                    # 检查目录名是否为中文
                    if folder_name in name_mapping[en_name]:
                        # 中文目录通过映射表转换
                        match_found = True
                        if num != folder_num:
                            try:
                                old_path = os.path.join(cref_path, folder)
                                new_name = f"{num}-{folder_name}"
                                new_path = os.path.join(cref_path, new_name)
                                if flag:
                                    subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                else:
                                    os.rename(old_path, new_path)
                                print(f"重命名文件夹: {folder} -> {new_name}")
                                for i, updated_path in enumerate(updated_paths):
                                    if old_path in updated_path:
                                        updated_paths[i] = updated_path.replace(old_path, new_path)
                            except Exception as e:
                                print(f"\033[91m重命名文件夹失败:\033[0m {str(e)}")
                                sysop_flag = True
                        break
                    else:
                        # 英文目录处理
                        folder_name_clean = ' '.join(folder_name.split())

                        if folder_name_clean == 'Basic Commands':
                            folder_name_clean = 'Basic Configuration'
                        else:
                            folder_name_clean = folder_name_clean.replace(' Commands', '')
                        # 比对序号和名称前缀
                        if folder_name_clean == en_name:
                            match_found = True
                            if num != folder_num:
                                try:
                                    old_path = os.path.join(cref_path, folder)
                                    new_name = f"{num}-{folder_name}"
                                    new_path = os.path.join(cref_path, new_name)
                                    if flag:
                                        subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                    else:
                                        os.rename(old_path, new_path)
                                    print(f"重命名文件夹: {folder} -> {new_name}")
                                    for i, updated_path in enumerate(updated_paths):
                                        if old_path in updated_path:
                                            updated_paths[i] = updated_path.replace(old_path, new_path)
                                except Exception as e:
                                    print(f"\033[91m重命名文件夹失败:\033[0m {str(e)}")
                                    sysop_flag = True
                            break

                if not match_found:
                    print(f"\033[93m警告：扉页中的 '{name}' 在命令参考中未找到对应的分册\033[0m")
                    sysop_flag = True
        else:
            print(f"\033[91m错误：找不到命令参考目录:\033[0m {cref_path}")
            sysop_flag = True

    except Exception as e:
        print(f"\033[91m处理文件出错:\033[0m {str(e)}")
        print(f"\033[91m遍历文件夹出错:\033[0m {str(e)}")
        sysop_flag = True
    print("命令参考处理完成！！！")
    if is_only_dir:
        print("程序执行完成!!!")
        return "-1"
    if not is_only_dir:
        # print(updated_paths)
        print("*" * 50)
        return updated_paths


if __name__ == '__main__':
    module_level_number_en(False, False)
